﻿using System;
using System.IO;
using System.Text;
using Dexter.Storage;

namespace Dexter.Security {
	public class EncryptionService : IEncryptionService {
		readonly IStorageProvider storageProvider;
		string encryptionKey;

		public EncryptionService ( IStorageProvider storageProvider ) {
			this.storageProvider = storageProvider;
		}

		#region IEncryptionService Members

		public string EncryptValue ( string value ) {
			return value.Encrypt ( encryptionKey );
		}

		public string Decrypt ( string encryptedValue ) {
			return encryptedValue.Decrypt ( encryptionKey );
		}

		public void CreateNewKey ( ) {
			CreateNewKey ( null );
		}

		public void CreateNewKey ( string key ) {
			var encryptFilePath = storageProvider.Combine ( storageProvider.PrivateRoot , "Setup\\encrypt.dxt" );

			if ( storageProvider.FileExist ( encryptFilePath ) ) {
				storageProvider.DeleteFile ( encryptFilePath );
			}

			string k = string.IsNullOrEmpty ( key )
			           	? Guid.NewGuid ( ).ToString ( )
			           	: key;

			using ( var ms = new MemoryStream ( ) ) {
				Encoding uniEncoding = Encoding.UTF8;

				ms.Write ( uniEncoding.GetBytes ( k ) , 0 , k.Length );
				ms.Seek ( 0 , SeekOrigin.Begin );

				storageProvider.SaveStream ( encryptFilePath , ms );
			}

			encryptionKey = k;
		}

		public bool IsKeyAssociated {
			get { return !string.IsNullOrEmpty ( encryptionKey ); }
		}

		#endregion
	}
}